import { Component, Vue } from 'vue-property-decorator'
import styles from './index.less'
import OperationCol from '@/components/OperationCol'
import service from '@/lib/service'
import { ElForm } from 'element-ui/types/form'
import ImagePreview from '@/components/ImagePreview'
import { formatStatus } from '@/lib/sealFormat'
import { desensitization } from '@/lib/utils'

import { userLicenseTypes, orgTypes, orgLicenseTypes } from '@/lib/sealFormat'
import { Action } from 'vuex-class'
import TableEmpty from '@/components/tableEmpty'

interface TableData {
  id: string
  orgName: string
  licenseNumber: string
  parentOrgName: string
  applyTime: string
  status: number
}

@Component({})
export default class AgencyAdministratorApply extends Vue {
  tableData: TableData[] = []

  private ruleForm: any = {
    applyCode: '',
    daterange: '',
    applyStatus: [],
    organizeName: '',
  }
  private pagesObj: any = {
    index: 1,
    size: 10,
    total: 0,
  }

  private dialogVisible: boolean = false
  private imgVisible = false
  private unBindVisible: boolean = false
  private unBindData: any = {}
  private unBindloading: boolean = false
  private unBindDataLoading: boolean = false
  private loading: boolean = false

  private applyPicUrl: string = ''
  private agencyAdministratorApplyDetail: any = {}
  @Action('applyPage/cancelApplyManager') private cancelApplyManager!: any
  @Action('applyPage/queryChildAndSealCount')
  private queryChildAndSealCount!: any

  protected render() {
    return (
      <div class={styles.agencyAdministratorApplyView}>
        <el-form {...{ props: { model: this.ruleForm } }} ref="elform">
          <div>
            <el-row>
              <el-col span={8}>
                <el-form-item label="申请授权机构">
                  <el-input
                    v-model={this.ruleForm.organizeName}
                    placeholder="请输入申请授权机构"
                  />
                </el-form-item>
              </el-col>
              <el-col span={8}>
                <el-form-item label="申请状态">
                  <el-select
                    v-model={this.ruleForm.applyStatus}
                    placeholder="默认全部"
                    size="mini"
                    multiple
                    collapse-tags
                  >
                    <el-option label="新增" value={1} />
                    <el-option label="待审核" value={2} />
                    <el-option label="审核通过" value={3} />
                    <el-option label="已撤回" value={4} />
                    <el-option label="已退回" value={6} />
                    <el-option label="已解绑" value={7} />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col span={8}>
                <el-form-item label="申请编号">
                  <el-input
                    v-model={this.ruleForm.applyCode}
                    placeholder="请输入申请编号"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col span={8}>
                <el-form-item label="创建日期">
                  <el-date-picker
                    v-model={this.ruleForm.daterange}
                    type="daterange"
                    range-separator="-"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </div>
          <div>
            <el-form-item>
              <el-button size="mini" type="primary" onClick={this.searchData}>
                搜索
              </el-button>
              <el-button size="mini" onClick={this.resetForm}>
                重置
              </el-button>
            </el-form-item>
          </div>
        </el-form>

        <p class="pt5">
          <el-button class="medium bg-color-blue" onClick={this.gotoApply}>
            新增机构印章管理员
          </el-button>
        </p>

        <el-table data={this.tableData} v-loading={this.loading}>
          <TableEmpty
            slot="empty"
            msg="暂无匹配的机构管理员申请记录"
            v-show={!this.loading}
          >
            <el-button type="primary" onClick={this.gotoApply}>
              前往申请印章管理员
            </el-button>
          </TableEmpty>
          <el-table-column
            prop="applyCode"
            label="申请编号"
            show-overflow-tooltip
          />
          <el-table-column
            prop="applyName"
            label="申请人姓名"
            show-overflow-tooltip
          />
          <el-table-column
            prop="applyOrganizeName"
            label="申请授权机构"
            show-overflow-tooltip
          />
          <el-table-column
            prop="createTime"
            label="创建时间"
            show-overflow-tooltip
          />
          <el-table-column
            prop="applyStatus"
            label="状态"
            show-overflow-tooltip
            {...{
              scopedSlots: {
                default: (scope: any) => {
                  return this.formatStatus(scope.row.applyStatus)
                },
              },
            }}
          />
          <el-table-column
            prop="id"
            label="操作"
            width="200"
            {...{
              scopedSlots: {
                default: (scope: any) => {
                  return (
                    <OperationCol
                      operations={this.filterOpera(scope.row)}
                      showNum={4}
                      row={scope.row}
                      index={scope.$index}
                    />
                  )
                },
              },
            }}
          />
        </el-table>
        {this.tableData && this.tableData.length > 0 && (
          <el-pagination
            style={{ display: this.pagesObj.total ? 'block' : 'none' }}
            onSize-change={this.handleSizeChange}
            onCurrent-change={this.handleCurrentChange}
            current-page={this.pagesObj.index}
            page-sizes={[10, 20, 30]}
            page-size={this.pagesObj.size}
            layout="total, sizes, prev, pager, next, jumper"
            total={this.pagesObj.total}
            pager-count={5}
          />
        )}

        <el-dialog
          class="agency-administrator-apply-dialog"
          title="机构印章管理员申请详情"
          visible={this.dialogVisible}
          before-close={() => {
            this.dialogVisible = false
          }}
          width="600px"
        >
          <div>
            <div>
              <h4>申请授权机构范围</h4>
              <el-row>
                <el-col span={12}>
                  <div>
                    <span>授权机构名称</span>
                    <span>
                      {this.agencyAdministratorApplyDetail.applyOrganizeName ||
                        '--'}
                    </span>
                  </div>
                  <div>
                    <span>证照类型</span>
                    <span>
                      {formatStatus(
                        orgLicenseTypes,
                        this.agencyAdministratorApplyDetail
                          .applyOrganizeLicenseType
                      ) || '--'}
                    </span>
                  </div>
                </el-col>
                <el-col span={12}>
                  <div>
                    <span>机构类型</span>
                    <span>
                      {formatStatus(
                        orgTypes,
                        this.agencyAdministratorApplyDetail.applyOrganizeType
                      ) || '--'}
                    </span>
                  </div>
                  <div>
                    <span>证照号码</span>
                    <span>
                      {this.agencyAdministratorApplyDetail
                        .applyOrganizeLicenseNumber || '--'}
                    </span>
                  </div>
                </el-col>
              </el-row>
            </div>
            <div>
              <h4>申请人基本信息</h4>
              <el-row>
                <el-col span={12}>
                  <div>
                    <span>申请人姓名</span>
                    <span>
                      {this.agencyAdministratorApplyDetail.applyName || '--'}
                    </span>
                  </div>
                  <div>
                    <span>申请人证件类型</span>
                    <span>
                      {formatStatus(
                        userLicenseTypes,
                        this.agencyAdministratorApplyDetail.applyLicenseType
                      ) || '--'}
                    </span>
                  </div>
                </el-col>
                <el-col span={12}>
                  <div>
                    <span>申请人手机号</span>
                    <span>
                      {desensitization(
                        this.agencyAdministratorApplyDetail.applyMobile
                      ) || '--'}
                    </span>
                  </div>
                  <div>
                    <span>申请人证件号</span>
                    <span>
                      {desensitization(
                        this.agencyAdministratorApplyDetail.applyLicenseNumber
                      ) || '--'}
                    </span>
                  </div>
                </el-col>
              </el-row>
            </div>
            {this.agencyAdministratorApplyDetail.applyPicUrl && (
              <div>
                <h4>申请表</h4>
                <div class="thumbnail" onClick={this.preview}>
                  <div class="hover-blank">
                    <img src={require('@/assets/preview.png')} />
                  </div>
                  <img src={this.agencyAdministratorApplyDetail.applyPicUrl} />
                </div>
              </div>
            )}
            <div>
              <h4>机构印章管理员申请信息</h4>
              <el-timeline>
                {this.agencyAdministratorApplyDetail.sealApplyOpsBOs &&
                  this.agencyAdministratorApplyDetail.sealApplyOpsBOs.map(
                    (activity: any, index: number) => (
                      <el-timeline-item key={index} timestamp={activity.time}>
                        <span
                          class={{ [styles.red]: activity.operatorType === 6 }}
                        >
                          {activity.operatorTypeName}
                        </span>
                        <span>{activity.content}</span>
                      </el-timeline-item>
                    )
                  )}
              </el-timeline>
            </div>
          </div>
          <span slot="footer" class="dialog-footer">
            <el-button
              onClick={() => {
                this.dialogVisible = false
              }}
            >
              关 闭
            </el-button>
          </span>
        </el-dialog>
        <ImagePreview
          visible={this.imgVisible}
          title="证明材料预览"
          url={this.applyPicUrl}
          onVisibleChange={(val: boolean) => {
            this.imgVisible = val
          }}
        />
        <el-dialog
          class={styles.unbindDialog}
          title="解除授权"
          visible={this.unBindVisible}
          before-close={() => {
            this.unBindVisible = false
          }}
          close-on-press-escape={false}
          close-on-click-modal={false}
          width="600px"
        >
          <p class={styles.tips}>
            <i class="el-icon-info" />
            解绑后无法查看与管理原有已授权的印章，解绑操作将无法恢复，请谨慎操作
          </p>
          <div class={styles.content}>
            <p>
              <span class={styles.title}>授权机构名称 </span>
              {this.unBindData.name}
            </p>
            <p v-loading={this.unBindDataLoading}>
              包含下级机构共
              <span class={styles.number}>{this.unBindData.children || 0}</span>
              个&nbsp; 包含已授权电子印章
              <span class={styles.number}>{this.unBindData.sealSize || 0}</span>
              枚
            </p>
          </div>
          <div slot="footer">
            <el-button
              onClick={() => {
                this.unBindVisible = false
              }}
            >
              关闭
            </el-button>
            <el-button
              type="primary"
              loading={this.unBindloading}
              onClick={this.unBindConfirm}
            >
              确认解绑
            </el-button>
          </div>
        </el-dialog>
      </div>
    )
  }
  private mounted() {
    this.getTableList()
  }
  private handleSizeChange(val: number) {
    this.pagesObj.index = 1
    this.pagesObj.size = val
    this.getTableList()
  }
  private handleCurrentChange(val: number) {
    this.pagesObj.index = val
    this.getTableList()
  }
  private async getTableList() {
    let createStartTime: any = ''
    let createEndTime: any = ''

    if (Array.isArray(this.ruleForm.daterange)) {
      ;[createStartTime, createEndTime] = this.ruleForm.daterange

      createStartTime = new Date(createStartTime)
      createEndTime = new Date(createEndTime)

      createStartTime.setDate(createStartTime.getDate() + 1)
      createEndTime.setDate(createEndTime.getDate() + 1)

      createStartTime = createStartTime
        .toISOString()
        .replace(/T.+/, 'T00:00:00')
      createEndTime = createEndTime.toISOString().replace(/T.+/, 'T23:59:59')
    }
    this.loading = true
    await this.$nextTick()
    await service({
      url: '/seal/rest/apply/myManagerApplyList',
      method: 'POST',
      body: {
        ...this.ruleForm,
        createStartTime,
        createEndTime,
        pageIndex: this.pagesObj.index,
        pageNumber: this.pagesObj.size,
      },
    }).then(res => {
      if (res.errCode === 0) {
        this.tableData = res.data.list
        this.pagesObj.total = res.data.total
      }
    })

    await this.$nextTick()
    this.loading = false
  }

  get getOperations() {
    const btns: any[] = [
      {
        id: 0,
        text: '详情',
        onClick: (index: number, rows: any) => {
          this.showDetail(rows)
        },
      },
      {
        id: 1,
        text: '删除',
        isDelete: true,
        onClick: (index: number, rows: any) => {
          this.delete(rows)
        },
      },
      {
        id: 2,
        text: '修改',
        onClick: (index: number, rows: any) => {
          this.update(rows)
        },
      },
      {
        id: 4,
        text: '撤回',
        isDelete: true,
        customWarning: '撤回当前申请后无法恢复，是否继续？',
        onClick: (index: number, rows: any) => {
          console.log(55555)
          this.resetApply(rows)
        },
      },
      {
        id: 5,
        text: '解除授权',
        onClick: (index: number, rows: any) => {
          this.unBind(rows)
        },
      },
    ]

    return btns
  }

  private filterOpera(row: any) {
    const status = row.applyStatus
    if (status === 1) {
      return this.getOperations.filter(
        (item: any) => item.id !== 4 && item.id !== 5
      )
    } else if (status === 2) {
      return this.getOperations.filter(
        (item: any) => item.id === 0 || item.id === 4
      )
    } else if (status === 3) {
      return this.getOperations.filter(
        (item: any) => item.id === 0 || item.id === 5
      )
    } else if (status === 4 || status === 7) {
      return this.getOperations.filter((item: any) => item.id === 0)
    } else if (status === 6) {
      return this.getOperations.filter(
        (item: any) => item.id !== 1 && item.id !== 5
      )
    }
  }

  private unBind(row: any) {
    this.unBindData.name = row.applyOrganizeName
    this.unBindData.applyId = row.applyId
    this.queryChildAndSealCount({ applyId: row.applyId }).then((res: any) => {
      this.unBindVisible = true
      this.unBindData.children = res.data.childOrganizeCount
      this.unBindData.sealSize = res.data.sealCount
    })
  }

  private unBindConfirm() {
    // 确认解绑
    this.$message.success('解除成功，已完成解绑')
    this.unBindloading = true
    this.cancelApplyManager({ applyId: this.unBindData.applyId })
      .then((res: any) => {
        this.unBindloading = false
        this.unBindVisible = false
        this.searchData()
      })
      .catch(() => {
        this.unBindloading = false
      })
  }

  private delete(row: any) {
    service({
      url: '/seal/rest/apply/deleteApply',
      method: 'POST',
      body: {
        applyId: row.applyId,
      },
    }).then(res => {
      if (res.errCode === 0) {
        this.$message.success('删除成功')
        this.searchData()
      }
    })
  }

  private resetApply(row: any) {
    service({
      url: '/seal/rest/apply/applyRecall',
      method: 'POST',
      body: {
        applyId: row.applyId,
      },
    }).then(res => {
      if (res.errCode === 0) {
        this.searchData()
      }
    })
  }

  private showDetail(row: any) {
    this.dialogVisible = true
    service({
      url: '/seal/rest/manager/queryManagerApplyDetail',
      method: 'POST',
      body: {
        applyId: row.applyId,
      },
    }).then(res => {
      console.log(res)
      if (res.errCode === 0) {
        this.agencyAdministratorApplyDetail = res.data
        this.applyPicUrl = this.agencyAdministratorApplyDetail.applyPicUrl
      }
    })
  }

  private update(row: any) {
    this.$router.push({
      name: 'administratorApply',
      params: {
        type: 'agencyAdministratorApply' || '',
      },
      query: { applyId: row.applyId },
    })
  }

  private gotoApply() {
    this.$router.push({
      name: 'administratorApply',
      params: {
        type: 'agencyAdministratorApply' || '',
      },
    })
  }

  private resetForm() {
    this.$refs.elform &&
      (this.$refs.elform as ElForm) &&
      (this.$refs.elform as ElForm).resetFields()
    this.ruleForm = {
      applyCode: '',
      daterange: '',
      applyStatus: [],
      organizeName: '',
    }
    this.searchData()
  }

  private searchData() {
    this.pagesObj.index = 1
    this.getTableList()
  }

  private preview() {
    this.imgVisible = true
  }

  /**
   * 生成状态标签
   * @param status 状态码
   */
  private formatStatus(status: number) {
    const applyStatus: any = {
      1: {
        label: '未提交',
        color: '#1890FF',
      },
      2: {
        label: '待审核', // 发起申请
        color: '#1890FF',
      },
      3: {
        label: '审核通过', // 审核通过
        color: '#52C41A',
      },
      4: {
        label: '已撤回', // 已撤回
        color: '#F5222D',
      },
      5: {
        label: '删除',
        color: '#F5222D',
      },
      6: {
        label: '已退回', // 审核退回：理由
        color: '#f5222d',
      },
      7: {
        label: '已解绑', // 解除授权
        color: '#f5222d',
      },
    }

    return (
      <div>
        <i
          style={{
            display: 'inline-block',
            backgroundColor: applyStatus[status].color,
            width: '10px',
            height: '10px',
            borderRadius: '100%',
            margin: '0 5px 0 0',
          }}
        />
        <span>{applyStatus[status].label}</span>
      </div>
    )
  }
}
